<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/logo.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/logo.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/logo.png">
  <link rel="mask-icon" href="/images/logo.png" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"gitee.com","root":"/","scheme":"Pisces","version":"7.7.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"./public/search.xml"};
  </script>

  <meta name="description" content="闭包和作用域是精通函数的必经之路，也是各种面试爱问的">
<meta property="og:type" content="article">
<meta property="og:title" content="精通函数：闭包和作用域">
<meta property="og:url" content="https://gitee.com/mamba666/mamba666.git/2021/04/12/%E7%B2%BE%E9%80%9A%E5%87%BD%E6%95%B0%EF%BC%9A%E9%97%AD%E5%8C%85%E5%92%8C%E4%BD%9C%E7%94%A8%E5%9F%9F/index.html">
<meta property="og:site_name" content="共你云雨">
<meta property="og:description" content="闭包和作用域是精通函数的必经之路，也是各种面试爱问的">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-04-12T02:32:08.699Z">
<meta property="article:modified_time" content="2021-06-12T02:26:22.061Z">
<meta property="article:author" content="Edison">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://gitee.com/mamba666/mamba666.git/2021/04/12/%E7%B2%BE%E9%80%9A%E5%87%BD%E6%95%B0%EF%BC%9A%E9%97%AD%E5%8C%85%E5%92%8C%E4%BD%9C%E7%94%A8%E5%9F%9F/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true
  };
</script>

  <title>精通函数：闭包和作用域 | 共你云雨</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>
	<a href="https://github.com/mamba666" target="_blank" rel="noopener" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">共你云雨</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
  </ul>

</nav>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/mamba666/mamba666.git/2021/04/12/%E7%B2%BE%E9%80%9A%E5%87%BD%E6%95%B0%EF%BC%9A%E9%97%AD%E5%8C%85%E5%92%8C%E4%BD%9C%E7%94%A8%E5%9F%9F/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="Edison">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="共你云雨">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          精通函数：闭包和作用域
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-04-12 10:32:08" itemprop="dateCreated datePublished" datetime="2021-04-12T10:32:08+08:00">2021-04-12</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-06-12 10:26:22" itemprop="dateModified" datetime="2021-06-12T10:26:22+08:00">2021-06-12</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E3%80%8AJavaScript%E5%BF%8D%E8%80%85%E7%A7%98%E7%B1%8D%E3%80%8B%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0/" itemprop="url" rel="index"><span itemprop="name">《JavaScript忍者秘籍》阅读笔记</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>闭包和作用域是精通函数的必经之路，也是各种面试爱问的</p>
<a id="more"></a>

<h2 id="理解闭包"><a href="#理解闭包" class="headerlink" title="理解闭包"></a>理解闭包</h2><p>先看一个最简单的闭包例子，其实不知道闭包之前也经常写这样的代码。即闭包允许函数访问并且操作函数外部的变量（下面的代码就操作了外部的变量 outerValue）。只要变量或者函数存在于声明函数的作用域内，闭包即可访问这些变量或者函数（下面的代码变量 outerValue 和函数 outerFunction 存在于同一作用域内。）</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> outerValue = <span class="string">"ninja"</span></span><br><span class="line">!<span class="function"><span class="keyword">function</span> <span class="title">outerFunction</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">	outerValue === <span class="string">"ninja"</span> ? log(<span class="string">"yes"</span>) : log(<span class="string">"no"</span>)</span><br><span class="line">&#125;()</span><br></pre></td></tr></table></figure>

<p>但是上面的代码平平无奇，无法显示出闭包的优势。下面再写一个凸显闭包优势的代码。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> outerValue = <span class="string">"samurai"</span></span><br><span class="line"><span class="keyword">let</span> later</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">outerFunction</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">	<span class="keyword">let</span> innerValue = <span class="string">"ninja"</span></span><br><span class="line">	<span class="function"><span class="keyword">function</span> <span class="title">innerFunction</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">		outerValue === <span class="string">"samurai"</span> ? log(<span class="string">"yes"</span>) : log(<span class="string">"no"</span>) <span class="comment">//yes,因为outerValue是全局变量，是全局可见的！</span></span><br><span class="line">		innerValue === <span class="string">"ninja"</span> ? log(<span class="string">"yes"</span>) : log(<span class="string">"no"</span>) <span class="comment">//yes</span></span><br><span class="line">	&#125;</span><br><span class="line">	later = innerFunction <span class="comment">//要知道函数也是引用类型</span></span><br><span class="line">&#125;</span><br><span class="line">outerFunction() <span class="comment">// 首先执行外部函数，将内部函数的引用指向 later</span></span><br><span class="line">later() <span class="comment">// 现在 later 成为了函数，执行内部函数</span></span><br></pre></td></tr></table></figure>

<p>记住两点：</p>
<ol>
<li>外部不可以访问内部的</li>
<li>内部可以访问外部</li>
</ol>
<h2 id="使用闭包"><a href="#使用闭包" class="headerlink" title="使用闭包"></a>使用闭包</h2><p>首先关注闭包的实用性和优势，在后续在探究其幕后所发生的。</p>
<h3 id="封装私有变量"><a href="#封装私有变量" class="headerlink" title="封装私有变量"></a>封装私有变量</h3><p>私有变量是对外部所隐藏的，但是原生 JavaScript 不支持，不过好在闭包可以模拟出私有变量，因为闭包有个属性，前面也提到过，即外部不可以访问内部</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 构造函数</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Ninja</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">	<span class="comment">// 定义一个私有变量</span></span><br><span class="line">	<span class="comment">// 在构造函数内的变量，除了使用 this 关键字的均为私有变量</span></span><br><span class="line">	<span class="keyword">let</span> feints = <span class="number">0</span></span><br><span class="line">	<span class="comment">// 读取私有变量</span></span><br><span class="line">	<span class="keyword">this</span>.getFeints = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> feints</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">// 修改私有变量</span></span><br><span class="line">	<span class="keyword">this</span>.feint = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">		feints++</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> ninja1 = <span class="keyword">new</span> Ninja() </span><br><span class="line">ninja1.feint() <span class="comment">// ninja1 调用 feint 方法，feints++，故 feints 变为1</span></span><br><span class="line">ninja1.feints === <span class="literal">undefined</span> ? log(<span class="string">'yes'</span>) : log(<span class="string">'no'</span>) <span class="comment">// 这里为 yes 是因为 feints 是私有变量，不能从外部直接访问内部，必须从内部返回出去</span></span><br><span class="line">ninja1.getFeints() === <span class="number">1</span> ? log(<span class="string">'yes'</span>) : log(<span class="string">'no'</span>) <span class="comment">//yes</span></span><br><span class="line"><span class="keyword">let</span> ninja2 = <span class="keyword">new</span> Ninja()</span><br><span class="line">ninja2.getFeints() === <span class="number">0</span> ? log(<span class="string">'yes'</span>) : log(<span class="string">'no'</span>) <span class="comment">//yes 每一个新的构造函数被创建出来，里面的属性都是不一样的，都有自己的作用域</span></span><br></pre></td></tr></table></figure>

<h3 id="回调函数"><a href="#回调函数" class="headerlink" title="回调函数"></a>回调函数</h3><ul>
<li>突然就悟出来了，只论这个<code>tick</code>变量，由于闭包的特性，外部不能访问内部变量，那么<code>tick</code>实际上是对全局隐藏的，如果将其置于全局中，那么就会造成污染</li>
</ul>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">"en"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"UTF-8"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">"X-UA-Compatible"</span> <span class="attr">content</span>=<span class="string">"IE=edge"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">"viewport"</span> <span class="attr">content</span>=<span class="string">"width=device-width, initial-scale=1.0"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">title</span>&gt;</span>Document<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">style</span>&gt;</span></span><br><span class="line"><span class="css">    <span class="selector-id">#box1</span>&#123;</span></span><br><span class="line"><span class="css">      <span class="comment">/* 如果没有这个定位属性，dom 元素就不会动了 */</span></span></span><br><span class="line">      position: absolute;</span><br><span class="line">      width: 100px;</span><br><span class="line">      height: 100px;</span><br><span class="line">      background-color: red;</span><br><span class="line">    &#125;</span><br><span class="line">  <span class="tag">&lt;/<span class="name">style</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">"box1"</span>&gt;</span>first box<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"></span><br><span class="line">  <span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="actionscript">    <span class="comment">// 定义一个 animateIt 函数</span></span></span><br><span class="line"><span class="actionscript">    <span class="comment">// 参数传入一个 dom 元素</span></span></span><br><span class="line"><span class="actionscript">    <span class="function"><span class="keyword">function</span> <span class="title">animateIt</span><span class="params">(elementId)</span></span>&#123;</span></span><br><span class="line"><span class="actionscript">      <span class="comment">// 将 dom 元素绑定在 ele 变量上</span></span></span><br><span class="line"><span class="javascript">      <span class="keyword">let</span> elem=<span class="built_in">document</span>.getElementById(elementId)</span></span><br><span class="line"><span class="actionscript">      <span class="comment">// 定义一个变量 tick</span></span></span><br><span class="line"><span class="javascript">      <span class="keyword">let</span> tick=<span class="number">0</span></span></span><br><span class="line"><span class="actionscript">      <span class="comment">// 定义一个计时器 timer</span></span></span><br><span class="line"><span class="actionscript">      <span class="comment">// setInterval 的作用是使里面的 callback 延时调用</span></span></span><br><span class="line"><span class="javascript">      <span class="keyword">let</span> timer=setInterval(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span></span><br><span class="line"><span class="actionscript">        <span class="comment">// 当 tick 小于100时，让这个 dom 元素的样式发生变化，然后 tick ++即可</span></span></span><br><span class="line">        if(tick&lt;100)&#123;</span><br><span class="line"><span class="actionscript">          elem.style.left=elem.style.top=tick+<span class="string">'px'</span></span></span><br><span class="line">          tick++</span><br><span class="line"><span class="actionscript">        &#125;<span class="keyword">else</span>&#123;</span></span><br><span class="line"><span class="actionscript">          <span class="comment">// 当 tick++ 到100之后，就使用 clearInterval 清除这个计时器</span></span></span><br><span class="line"><span class="actionscript">          <span class="comment">// 使用了计时器一定要记得清除，不然会对系统造成轻微的占用</span></span></span><br><span class="line">          clearInterval(timer)</span><br><span class="line"><span class="javascript">          tick===<span class="number">100</span>?<span class="built_in">console</span>.log(<span class="string">'100'</span>):<span class="built_in">console</span>.log(<span class="string">'not 100'</span>)</span></span><br><span class="line">        &#125;</span><br><span class="line">      &#125;,10)</span><br><span class="line">    &#125;</span><br><span class="line"><span class="actionscript">    animateIt(<span class="string">'box1'</span>)</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h2 id="通过执行上下文来跟踪代码"><a href="#通过执行上下文来跟踪代码" class="headerlink" title="通过执行上下文来跟踪代码"></a>通过执行上下文来跟踪代码</h2><ul>
<li>首先要搞明白，函数执行上下文和执行上下文有着本质的区别，函数执行上下文讨论的是<code>this</code>指向问题，而执行上下文是整个代码运行的一个顺序。</li>
</ul>
<p>既然这么复杂，那么先来创建一个执行上下文</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">skull</span>(<span class="params">ninja</span>) </span>&#123;</span><br><span class="line">	report(ninja + <span class="string">'  edison'</span>)</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">report</span>(<span class="params">msg</span>) </span>&#123;</span><br><span class="line">	<span class="built_in">console</span>.log(msg)</span><br><span class="line">&#125;</span><br><span class="line">skull(<span class="string">'kuma'</span>) <span class="comment">// kuma edison</span></span><br><span class="line">skull(<span class="string">'yoshi'</span>) <span class="comment">// yoshi edison</span></span><br></pre></td></tr></table></figure>

<p>逻辑就是首先执行全局代码，直到<code>skull(&#39;kuma&#39;)</code>，然后在其内部再次发现函数 report 。</p>
<p>总结一下：</p>
<ol>
<li>每个 JavaScript 程序只能创建一个全局执行上下文，并且从全局上下文开始执行。在 vue 这种单页框架中，每个单独的页面都有一个全局执行上下文。当执行全局代码时，其处于活跃状态。</li>
<li>可以通过浏览器的调试工具看到<code>调用堆栈</code>项目。</li>
</ol>
<h2 id="使用词法环境跟踪变量的作用域"><a href="#使用词法环境跟踪变量的作用域" class="headerlink" title="使用词法环境跟踪变量的作用域"></a>使用词法环境跟踪变量的作用域</h2><pre><code>词法环境通常就是我们说的作用域</code></pre><p> 例如如下代码，console.log 语句在打印 ninja 变量时，就会进行词法环境查询。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">ninja = <span class="string">"hola"</span></span><br><span class="line"><span class="built_in">console</span>.log(ninja)</span><br></pre></td></tr></table></figure>

<h3 id="代码嵌套"><a href="#代码嵌套" class="headerlink" title="代码嵌套"></a>代码嵌套</h3><pre><code>词法环境是基于代码嵌套的</code></pre><p>可以看到内部代码可以访问到所有的外部变量，而外部变量想访问内部变量就会报错（ReferenceError 即引用错误，指压根找不到这个变量）</p>
<p>这种写法其实很常见，可是有一个问题，JavaScript 是如何跟踪这些变量的呢？是如何判断变量是否为可访问的呢？ 这就是词法环境的作用了。接下来将详细分析。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> ninja = <span class="string">"hello"</span></span><br><span class="line">!<span class="function"><span class="keyword">function</span> <span class="title">skulk</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">	<span class="keyword">let</span> action = <span class="string">"skulking"</span></span><br><span class="line">	log(reportNum) <span class="comment">//ReferenceError: reportNum is not defined</span></span><br><span class="line">	<span class="function"><span class="keyword">function</span> <span class="title">report</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">		<span class="keyword">let</span> reportNum = <span class="number">3</span></span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; reportNum; i++) &#123;</span><br><span class="line">			log(ninja + <span class="string">' '</span> + action + <span class="string">' '</span> + i)</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	report()</span><br><span class="line">&#125;()</span><br></pre></td></tr></table></figure>

<h3 id="代码嵌套与词法环境"><a href="#代码嵌套与词法环境" class="headerlink" title="代码嵌套与词法环境"></a>代码嵌套与词法环境</h3><pre><code>如果在当前环境中无法查找到变量，就会向外部环境去查找</code></pre><p>当查找 intro 时，刚好在当前环境 report 中，很幸运。可是在查找 action 时，当前环境并没有此变量，于是就会向外部环境去找寻，发现在 report 环境之外的 skulk 环境有 action 变量，于是查找结束</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> ninja = <span class="string">"hello"</span></span><br><span class="line">!<span class="function"><span class="keyword">function</span> <span class="title">skulk</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">	<span class="keyword">let</span> action = <span class="string">"skulking"</span></span><br><span class="line">	!<span class="function"><span class="keyword">function</span> <span class="title">report</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">		<span class="keyword">let</span> intro = <span class="string">"Aha!"</span></span><br><span class="line">		intro = <span class="string">'Aha!'</span> ? log(<span class="string">'Aha!'</span>) : log(<span class="string">'not Aha!'</span>)</span><br><span class="line">		action = <span class="string">'skulking!'</span> ? log(<span class="string">'skulking!'</span>) : log(<span class="string">'not skulking!'</span>)</span><br><span class="line">		ninja = <span class="string">'hello!'</span> ? log(<span class="string">'hello!'</span>) : log(<span class="string">'not hello!'</span>)</span><br><span class="line">	&#125;()</span><br><span class="line">&#125;()</span><br></pre></td></tr></table></figure>

<h2 id="理解-JavaScript-的变量类型"><a href="#理解-JavaScript-的变量类型" class="headerlink" title="理解 JavaScript 的变量类型"></a>理解 JavaScript 的变量类型</h2><p>有三种定义变量的方式：var let const 。 如何分类呢？大致上可以从可变性和与词法环境的关系上去分类。</p>
<h3 id="变量的可变性"><a href="#变量的可变性" class="headerlink" title="变量的可变性"></a>变量的可变性</h3><ul>
<li>const 独一份，其定义的变量是不可变的</li>
<li>如果强行给 const 变量重新赋值，那么就会出现类型错误：给常量变量赋值</li>
<li>如果要定义 const 变量，那么必须要给其赋值一个初始值，不然会报错</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> something = <span class="string">'hello'</span></span><br><span class="line">something = <span class="string">'nihao'</span></span><br><span class="line"><span class="comment">// TypeError: Assignment to constant variable.</span></span><br></pre></td></tr></table></figure>

<p>那么为什么 const 如此不同呢？</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> hello1 = <span class="string">'nihao'</span></span><br><span class="line">hello1 === <span class="string">'nihao'</span> ? log(<span class="string">'yes'</span>) : log(<span class="string">'no'</span>) <span class="comment">//yes</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 尝试对 const 变量进行修改</span></span><br><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">	hello1 = <span class="string">'caonima'</span></span><br><span class="line">	log(<span class="string">'modify successfully'</span>)</span><br><span class="line">&#125; <span class="keyword">catch</span> (error) &#123;</span><br><span class="line">	log(<span class="string">'The modification was not successful'</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> hello2 = &#123;&#125;</span><br><span class="line"><span class="comment">// const hello2 = &#123; chinaCurse: 'CNM' &#125;</span></span><br><span class="line"><span class="comment">// 不可以再次对 hello2 进行重新赋值，但是可以尝试以下给 hello2 对象赋值</span></span><br><span class="line">hello2.chinaCurse = <span class="string">'CNM'</span></span><br><span class="line">log(hello2) <span class="comment">// &#123; chinaCurse: 'CNM' &#125;</span></span><br></pre></td></tr></table></figure>

<p>通过上面的代码可以发现，const 变量不能重新赋值，但是却可以修改，所以 const 并不是一成不变的。</p>
<ul>
<li>总结一下：const 变量只能在声明时被初始化一次，之后就不被允许在将全新的值赋值给 const 变量。但是我们<strong>可以去修改 const 变量，只是不能重写。</strong></li>
</ul>
<h3 id="关键字与词法环境的环境"><a href="#关键字与词法环境的环境" class="headerlink" title="关键字与词法环境的环境"></a>关键字与词法环境的环境</h3><pre><code>通俗易懂的说，根据作用域来分 let const 为一类，var 为另一类</code></pre><h4 id="var"><a href="#var" class="headerlink" title="var"></a>var</h4><ul>
<li>以下代码可以分成三个环境：全局、函数、块级</li>
<li>块级作用域定义的变量 i ，forMessage 却能被块级作用域的外面访问到。</li>
<li>关键字 var 可以忽略这种块级作用域，所以产生了这种情况</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> globalNinja = <span class="string">'Yoshi'</span></span><br><span class="line">!<span class="function"><span class="keyword">function</span> <span class="title">reportActivity</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">	<span class="keyword">var</span> functionActivity = <span class="string">'junmping'</span></span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">1</span>; i &lt; <span class="number">3</span>; i++) &#123;</span><br><span class="line">		<span class="keyword">var</span> forMessage = globalNinja + <span class="string">' '</span> + functionActivity</span><br><span class="line">		forMessage === <span class="string">'Yoshi junmping'</span> ? log(<span class="string">'yes1'</span>) : log(<span class="string">'no1'</span>)</span><br><span class="line">		log(<span class="string">'current:  '</span> + i)</span><br><span class="line">	&#125;</span><br><span class="line">	i === <span class="number">3</span> &amp;&amp; forMessage === <span class="string">'Yoshi junmping'</span> ? log(<span class="string">'yes2'</span>) : log(<span class="string">'no2'</span>)</span><br><span class="line">&#125;()</span><br><span class="line">log(functionActivity) <span class="comment">//ReferenceError: functionActivity is not defined</span></span><br><span class="line">log(i) <span class="comment">//ReferenceError: i is not defined</span></span><br><span class="line">log(forMessage) <span class="comment">//ReferenceError: forMessage is not defined</span></span><br></pre></td></tr></table></figure>

<h4 id="const-let"><a href="#const-let" class="headerlink" title="const let"></a>const let</h4><p>使用 const let 重新编写上面的代码，可以发现三元运算那里直接报错引用错误，因为 i 并未被定义，可是在函数环境中明明定义了变量 i ，这就是 const 和 let 的魔力所在。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> globalNinja = <span class="string">'Yoshi'</span></span><br><span class="line">!<span class="function"><span class="keyword">function</span> <span class="title">reportActivity</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">	<span class="keyword">let</span> functionActivity = <span class="string">'junmping'</span></span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">1</span>; i &lt; <span class="number">3</span>; i++) &#123;</span><br><span class="line">		<span class="keyword">let</span> forMessage = globalNinja + <span class="string">' '</span> + functionActivity</span><br><span class="line">		forMessage === <span class="string">'Yoshi junmping'</span> ? log(<span class="string">'yes1'</span>) : log(<span class="string">'no1'</span>)</span><br><span class="line">		log(<span class="string">'current:  '</span> + i)</span><br><span class="line">	&#125;</span><br><span class="line">	i === <span class="number">3</span> &amp;&amp; forMessage === <span class="string">'Yoshi junmping'</span> ? log(<span class="string">'yes2'</span>) : log(<span class="string">'no2'</span>) <span class="comment">// ReferenceError: i is not defined</span></span><br><span class="line">&#125;()</span><br></pre></td></tr></table></figure>

<h4 id="在词法环境中注册标识符"><a href="#在词法环境中注册标识符" class="headerlink" title="在词法环境中注册标识符"></a>在词法环境中注册标识符</h4><h2 id="研究闭包工作的原理"><a href="#研究闭包工作的原理" class="headerlink" title="研究闭包工作的原理"></a>研究闭包工作的原理</h2>
    </div>

    
    
    

      <footer class="post-footer">

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2021/04/09/%E5%87%BD%E6%95%B0%E8%BF%9B%E9%98%B6%EF%BC%9A%E7%90%86%E8%A7%A3%E5%87%BD%E6%95%B0%E7%9A%84%E8%B0%83%E7%94%A8/" rel="prev" title="函数进阶：理解函数的调用">
      <i class="fa fa-chevron-left"></i> 函数进阶：理解函数的调用
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/06/12/%E6%97%B6%E9%97%B4%E5%A4%8D%E6%9D%82%E5%BA%A6%E4%B8%8E%E7%A9%BA%E9%97%B4%E5%A4%8D%E6%9D%82%E5%BA%A6/" rel="next" title="时间复杂度与空间复杂度">
      时间复杂度与空间复杂度 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  

  </div>


          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#理解闭包"><span class="nav-number">1.</span> <span class="nav-text">理解闭包</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#使用闭包"><span class="nav-number">2.</span> <span class="nav-text">使用闭包</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#封装私有变量"><span class="nav-number">2.1.</span> <span class="nav-text">封装私有变量</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#回调函数"><span class="nav-number">2.2.</span> <span class="nav-text">回调函数</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#通过执行上下文来跟踪代码"><span class="nav-number">3.</span> <span class="nav-text">通过执行上下文来跟踪代码</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#使用词法环境跟踪变量的作用域"><span class="nav-number">4.</span> <span class="nav-text">使用词法环境跟踪变量的作用域</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#代码嵌套"><span class="nav-number">4.1.</span> <span class="nav-text">代码嵌套</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#代码嵌套与词法环境"><span class="nav-number">4.2.</span> <span class="nav-text">代码嵌套与词法环境</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#理解-JavaScript-的变量类型"><span class="nav-number">5.</span> <span class="nav-text">理解 JavaScript 的变量类型</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#变量的可变性"><span class="nav-number">5.1.</span> <span class="nav-text">变量的可变性</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#关键字与词法环境的环境"><span class="nav-number">5.2.</span> <span class="nav-text">关键字与词法环境的环境</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#var"><span class="nav-number">5.2.1.</span> <span class="nav-text">var</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#const-let"><span class="nav-number">5.2.2.</span> <span class="nav-text">const let</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#在词法环境中注册标识符"><span class="nav-number">5.2.3.</span> <span class="nav-text">在词法环境中注册标识符</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#研究闭包工作的原理"><span class="nav-number">6.</span> <span class="nav-text">研究闭包工作的原理</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">Edison</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">124</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">21</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">19</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
</div>
  <div class="powered-by">山高水远  一定相见
  </div>
<div></div>
<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">至今已写107.1k字</span>
</div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

</body>
</html>
